<?php
namespace app\demo_record\widget;

use think\Config;
use think\View;

class ListWidget
{
    public $fields=[];
    public $rows=[];
    public $list=[];
    public $action;
    public function setFields($fields)
    {
        $this->fields=$fields;
    }
    public function setRows($rows)
    {
        $this->rows=array_merge($this->rows,$rows);
    }
    public function setItemActionCallback($cb)
    {
        $this->action=$cb;
    }
    public function fetchTableWidget($template='demo_record@list_widget/table')
    {
        $view = new View();
        $view->assign("co",$this);
        return $view->fetch($template);
    }
    public function getHeads($content)
    {
        $ths=[];
        foreach($this->fields as $key => $field){
            $title = isset($field["title"]) ? $field["title"] : $key;
            $width = isset($field["width"]) ? ' width="'.$field["width"].'"' : "";
            $code= "return \"$content\";";
            $ths[] = eval($code);
        }
        return implode("",$ths);
    }
    public function getRowData($data,$content)
    {
        $tds=[];
        foreach($this->fields as $key => $field){
            $value = isset($data[$key]) ? $data[$key] : "";
            $code= "return \"$content\";";
            $tds[] = eval($code);
        }
        return implode("",$tds);
    }
    public function getActions($data,$content)
    {
        $links=[];
        $cb=$this->action;
        $actions=$cb($data);
        foreach($actions as $item){
            if(isset($item["type"]) && $item["type"]==="ajax" && isset($item["flag"]) && $item["flag"]==="delete"){
                $class=' class="js-ajax-delete"';
            }
            else{
                $class='';
            }
            $href=' href="'.$item["url"].'"';
            $title=$item["title"];
            $code= "return \"$content\";";
            $links[] = eval($code);
        }
        return implode("&nbsp;",$links);
    }
    public $itemActions=[];
    public $itemActionsCallback=null;
    public function getItemActions($item)
    {
        if(method_exists($this,"itemActionsCallback")){
            $cb=$this->itemActionsCallback;
            return $cb($item);
        }
        elseif($this->itemActions){
            $itemActions=[];
            foreach($this->itemActions as $action){
                $action["url"]=url($action["name"],['id'=>$item['id']]);
            }
            return $itemActions;
        }
        else{
            return [];
        }
    }
}
